<?php
/**
 * role
 * 角色
 * @author Administrator
 * @version
 */
class Model_Tables_Role extends Zend_Db_Table_Abstract {
    /**
     * The default table name
     */
    protected $_name = 'role';
    
    public function add( $params )
    {
        $data = array(
		'name' => $params['name'],
		'description' => $params['description'],
		'ipaccess' => $params['ipaccess'],
		'listorder' => $params['listorder'],
		'disabled' => $params['disabled'],
        );
        return $this->insert($data);
    }
    public function modify( $params, $roleid )
    {
        $data = array(
		'name' => $params['name'],
		'description' => $params['description'],
		'ipaccess' => $params['ipaccess'],
		'listorder' => $params['listorder'],
		'disabled' => $params['disabled'],
        );
        $where = 'roleid = '.$roleid ;
        return $this->update($data , $where );
    }
    public function modifyAjax( $roleid, $field, $value )
    {
    	$data = array($field => $value);
        $where = 'roleid = '.$roleid;
        return $this->update($data , $where );
    }
	public function modifyAjaxRevers( $field ,$pri)
    {
    	$db = $this->getAdapter();
    	$sql = "update role set  $field =not  $field  where roleid='$pri'";
		echo $sql;
    	return $db->query($sql);
    }
    
    
    public function del( $roleid )
    {
//     	$where = 'roleid = '.$roleid;
//        return $this->delete($where);
//        
        $db = $this->getAdapter();
    	$db->beginTransaction();
		try {
			$where = $db->quoteInto('roleid = ?',$roleid);
        	$this->delete($where);
        	$sqladmin = $db->quoteInto("delete from admin_role where roleid =?",$roleid);
		    $db->query($sqladmin);
		    $sqlpriv = $db->quoteInto("delete from admin_role_priv where roleid =?",$roleid);
		    $db->query($sqlpriv);
		    $db->commit();
		} catch (Exception $e) {
		    $db->rollBack();
		    return false;
		}
		return true;
        
        
    }
    public function getInfo($roleid)
    {
        $row = $this->fetchRow('roleid = ' . $roleid);
        if (!$row) {
        	return null;
        }
        else
        {
        	return $row->toArray();
        }
    }
    public function getInfos($roleids)
    {
    	$row = $this->fetchRow('roleid in( ' . $roleids .')');
    	if (!$row) {
    		return null;
    	}
    	else
    	{
    		return $row->toArray();
    	}
    }
    public function getCount($s = "")
    { 
        $select = $this->select()->from($this->_name,'count(*) as num');
    	if($s!="")  
    	{
    		$db = $this->getAdapter();
			$where = $db->quoteInto("name like ?", "%$s%");
    		$select = $select->where($where);
    	}
        $result = $this->fetchRow($select)->num;
        return $result;
    }
    public function getList($page, $numPerPage = 10,$s= "")
    {
    	$page = (1>$page) ? 1 : $page;
    	$offset = ($page-1)*$numPerPage;
        $orderby = array('roleid');
        if($s!="")     
		{
			$db = $this->getAdapter();
			$where = $db->quoteInto("name like ?", "%$s%");
		}  
        $result = $this->fetchAll($where,$orderby, $numPerPage, $offset )->toArray();
        return $result;
    }
    /**
     * 获取角色名称列表
     */
    public function getNameList()
    {
        $select = $this->select()->from($this->_name, array('roleid', 'name'));
        $result = $this->fetchAll($select);
        return $result->toArray();
    }
    /**
     * 获取资源列表，以数组形式返回
     */
    public function getResourceList()
    {
    	$db = $this->getAdapter();		
		$sql = "select distinct resourcegroup from resource";
		$result = $db->query($sql);
		$rows = $result->fetchAll();
		for($i=0;$i<count($rows);$i++)
		{
			$sql = "select id,resourcename from resource where resourcegroup='".$rows[$i]["resourcegroup"]."'";
			$result = $db->query($sql)->fetchAll();
			$priv = array();
	        if (!empty($result))
	        {
	            foreach ($result as $item)
	            {
	                $priv[$item['id']] = $item['resourcename'];
	            }
	        }
			$rows[$i]["priv"]=$priv;
		}
		return $rows;
    }
    /*
     * 获取工作流步骤列表
     */
	public function getWorkFlowProcessList()
    {
    	$db = $this->getAdapter();		
		$sql = "select workflowid, name from workflow ";
		$result = $db->query($sql);
		$rows = $result->fetchAll();
		for($i=0;$i<count($rows);$i++)
		{
			$sql = "select processid,name from process where workflowid = '".$rows[$i]["workflowid"]."'";
			$result = $db->query($sql)->fetchAll();
			$priv = array();
	        if (!empty($result))
	        {
	            foreach ($result as $item)
	            {
	                $priv[$item['processid']] = $item['name'];
	            }
	        }
			$rows[$i]["priv"]=$priv;
		}
		return $rows;
    }
    //修改角色权限
    public function modifyPriv($roleid,$resource,$process)
    {
    	$db = $this->getAdapter();	
    	$deletesql = "delete from admin_role_priv where roleid = '$roleid'";
    	$updateMenuRolesTemp = "update menu set roleids = concat(replace(roleids,',$roleid,',','),$roleid,',') where resourceid=? ";
    	$db->beginTransaction();
			try {
			    $db->query($deletesql);			    
			    foreach($resource as $v)
			    {
			    	$updateMenuRoles = $db->quoteInto($updateMenuRolesTemp,$v);
			    	$db->query($updateMenuRoles);
			    	$insertsql="insert into admin_role_priv(roleid, field, value) values ($roleid, 'resource','$v')";
			    	$db->query($insertsql);
			    }
				foreach($process as $v)
			    {
			    	$insertsql="insert into admin_role_priv(roleid, field, value) values ($roleid, 'process','$v')";
			    	$db->query($insertsql);
			    }
			    $db->commit();
			} catch (Exception $e) {
				$db->rollBack();
			    return false;
			}
		return true;
    }
    /*
     * 获取角色权限,返回字符串格式
     */
    public function getRolePriv($roleid,$field)
    {
    	$result = "";
    	if($field=="resource"||$field=="process")
    	{
    		$db = $this->getAdapter();
    		$selectsql = "select GROUP_CONCAT(value) as v from admin_role_priv where roleid = '$roleid' and field = '$field' group by roleid";
    		$result = $db->query($selectsql)->fetchAll();
    		if (!empty($result))
	        {
	        	$result = $result[0]['v'];	            
	        }
    	}
    	return $result;
    }
    /*
     * 获取角色名称列表
     */
 	public function getRoleList()
    {
        $select = $this->select()->from($this->_name, array('roleid', 'name'))
        ->where("disabled=0");
        $result = $this->fetchAll($select);
    	$roles = array();
        if (!empty($result))
	        {
	            foreach ($result as $item)
	            {
	                $roles[$item['roleid']] = $item['name'];
	            }
	        }
        return $roles;
    }
    /***
     * 根据角色编号取出所有mvc权限
     * 可以使用数据缓存来优化，暂时未做
     */
    public function getMvcAct($roleid)
    {
    	$db = $this->getAdapter();
    	$selectsql = "select resource.mvcaction mvcact from 
					 	admin_role_priv left join resource on admin_role_priv.value = resource.id
						where field = 'resource' and admin_role_priv.roleid in($roleid)";
    	$result = $db->query($selectsql)->fetchAll();
    	$str = "";
    	foreach($result as $item){
    		$str .= $item["mvcact"] . ",";
    	}
     	return explode(",", strtolower($str));
    }
}